class Node(object):
    def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight):
        self.val = val
        self.isLeaf = isLeaf
        self.topLeft = topLeft
        self.topRight = topRight
        self.bottomLeft = bottomLeft
        self.bottomRight = bottomRight


class Solution(object):
    def intersect(self, quadTree1, quadTree2):
        if quadTree1.isLeaf and quadTree2.isLeaf:
            quadTree1.val = quadTree1.val | quadTree2.val
        else:
            if quadTree1.isLeaf:
                quadTree1.isLeaf = 0
                quadTree1.topLeft = Node(quadTree1.val, 1, None, None, None, None)
                quadTree1.topRight = Node(quadTree1.val, 1, None, None, None, None)
                quadTree1.bottomLeft = Node(quadTree1.val, 1, None, None, None, None)
                quadTree1.bottomRight = Node(quadTree1.val, 1, None, None, None, None)
            if quadTree2.isLeaf:
                quadTree2.isLeaf = 0
                quadTree2.topLeft = Node(quadTree2.val, 1, None, None, None, None)
                quadTree2.topRight = Node(quadTree2.val, 1, None, None, None, None)
                quadTree2.bottomLeft = Node(quadTree2.val, 1, None, None, None, None)
                quadTree2.bottomRight = Node(quadTree2.val, 1, None, None, None, None)
            quadTree1.topLeft = self.intersect(quadTree1.topLeft, quadTree2.topLeft)
            quadTree1.topRight = self.intersect(quadTree1.topRight, quadTree2.topRight)
            quadTree1.bottomLeft = self.intersect(quadTree1.bottomLeft, quadTree2.bottomLeft)
            quadTree1.bottomRight = self.intersect(quadTree1.bottomRight, quadTree2.bottomRight)
            if quadTree1.topLeft.isLeaf and quadTree1.topRight.isLeaf and quadTree1.bottomLeft.isLeaf and quadTree1.bottomRight.isLeaf and quadTree1.topLeft.val == quadTree1.topRight.val == quadTree1.bottomLeft.val == quadTree1.bottomRight.val:
                quadTree1.isLeaf = 1
                quadTree1.val = quadTree1.topLeft.val
                quadTree1.topLeft = None
                quadTree1.topRight = None
                quadTree1.bottomLeft = None
                quadTree1.bottomRight = None
        return quadTree1
